
//
//  VideoVC.m
//  SeeFood
//
//  Created by 纪洪波 on 15/11/24.
//  Copyright © 2015年 纪洪波. All rights reserved.
//

#import "VideoVC.h"
#import "VideoView.h"
#import "PrefixHeader.pch"
#import "AVPlayerViewController.h"
#import "AppDelegate.h"
#import "UIView+UIView_Frame.h"
#import "CoreDataManager.h"

@interface VideoVC () <UIScrollViewDelegate>
@property (nonatomic, retain) UIScrollView             *scroll;
@property (nonatomic, retain) UIPageControl            *page;

@property (nonatomic, retain) VideoView *leftView;
@property (nonatomic, retain) VideoView *middleView;
@property (nonatomic, retain) VideoView *rightView;
@property (nonatomic, retain) NSMutableArray *modelArray;
@property (nonatomic, assign) NSInteger middleImageIndex;
@property (nonatomic ,copy  ) NSString       *nextPageUrl;
@property (nonatomic ,copy  ) NSURL       *url;
@end

@implementation VideoVC

- (void)viewDidLoad {
    [super viewDidLoad];
//    self.tabBarController.tabBar.hidden = YES;
    self.view.backgroundColor = [UIColor blackColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    
//    NSArray *nib = [[NSBundle mainBundle]loadNibNamed:@"VideoView"owner:self options:nil];
//    self.leftView = [nib objectAtIndex:0];
//    self.middleView = [nib objectAtIndex:0];
//    self.rightView = [nib objectAtIndex:0];
    
    
    _middleImageIndex = 0;
    [self createUI];
    [self getResourse];
}

//  请求网络数据
- (void)getResourse {
    NSString *transString = [@"开胃" stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSString *stringUrl = [NSString stringWithFormat:@"http://baobab.wandoujia.com/api/v1/videos?num=10&categoryName=%@", transString];
    self.url = [NSURL URLWithString:stringUrl];
    [[[NSURLSession sharedSession] dataTaskWithURL:self.url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSLog(@"%@",self.url);
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        self.nextPageUrl = [NSString stringWithFormat:@"%@&vc=125&u=368b8de74a9593712417679fd40adc8d79436584&v=1.8.1&f=iphone",[dic valueForKey:@"nextPageUrl"]];
        self.modelArray =[VideoModel jsonToModel:dic];
        
        [self performSelectorOnMainThread:@selector(mainThreadAction) withObject:nil waitUntilDone:YES];
    }]resume];
}

- (void)mainThreadAction {
    [self.leftView setValueWithVideoModel:self.modelArray[self.middleImageIndex == 0 ? self.modelArray.count - 1 : self.middleImageIndex - 1]];
    [self.middleView setValueWithVideoModel:self.modelArray[self.middleImageIndex]];
    [self.rightView setValueWithVideoModel:self.modelArray[self.middleImageIndex == self.modelArray.count - 1 ? 0 : self.middleImageIndex + 1]];
}

- (void)createUI {
    
    self.scroll = [[UIScrollView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.scroll.contentSize = CGSizeMake(KScreenWidth * 3, KScreenHeight);
    self.scroll.contentOffset = CGPointMake(KScreenWidth, 0);
    self.scroll.backgroundColor = [UIColor blackColor];
    self.scroll.pagingEnabled = YES;
    self.scroll.delegate = self;
    [self.view addSubview:self.scroll];
    self.scroll.showsHorizontalScrollIndicator = NO;
    
    self.leftView = [[VideoView alloc]init];
//    [self.leftView setValueWithVideoModel:self.modelArray[self.middleImageIndex == 0 ? self.modelArray.count - 1 : self.middleImageIndex - 1]];
    self.leftView.frame = CGRectMake(0, 0, KScreenWidth, KScreenHeight);
    [self.scroll addSubview:self.leftView];
    
    self.middleView = [[VideoView alloc]init];
//    [self.middleView setValueWithVideoModel:self.modelArray[self.middleImageIndex]];
    self.middleView.frame = CGRectMake(KScreenWidth, 0, KScreenWidth, KScreenHeight);
    [self.scroll addSubview:self.middleView];
    [self.middleView.playButton addTarget:self action:@selector(playVedio) forControlEvents:UIControlEventTouchUpInside];
        [self.middleView.like addTarget:self action:@selector(like:) forControlEvents:UIControlEventTouchUpInside];
//    self.middleView.backImage.x = 20;
    //    [self.middleView.download addTarget:self action:@selector(downloadAction:) forControlEvents:UIControlEventTouchUpInside];
    
    self.rightView = [[VideoView alloc]init];
//    [self.rightView setValueWithVideoModel:self.modelArray[self.middleImageIndex == self.modelArray.count - 1 ? 0 : self.middleImageIndex + 1]];
    self.rightView.frame = CGRectMake(KScreenWidth * 2, 0, KScreenWidth, KScreenHeight);
    [self.scroll addSubview:self.rightView];
    
    self.page = [[UIPageControl alloc]init];
    CGSize size = [self.page sizeForNumberOfPages:self.modelArray.count];
    self.page.frame = CGRectMake((KScreenWidth - size.width)/2, KScreenHeight - 60, size.width, size.height);
    self.page.numberOfPages = self.modelArray.count;
    self.page.currentPage = self.middleImageIndex;
    [self.page addTarget:self action:@selector(pageAction:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:self.page];
}

- (void)like:(UIButton *)button {
    if (!button.selected) {
        [[CoreDataManager shareInstance]insertDataWithModel:self.modelArray[_middleImageIndex]];
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"收藏成功" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:alert animated:YES completion:^{
            [self performSelector:@selector(alertDismiss:) withObject:alert afterDelay:1];
        }];
    }else {
        VideoModel *model = self.modelArray[_middleImageIndex];
        [[CoreDataManager shareInstance]deleteDataWithID:model.id];
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"收藏删除成功" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:alert animated:YES completion:^{
            [self performSelector:@selector(alertDismiss:) withObject:alert afterDelay:1];
        }];
        [[CoreDataManager shareInstance]deleteDataWithID:model.id];
    }
    button.selected = !button.selected;
}

- (void)alertDismiss:(UIAlertController *)alert{
    [alert dismissViewControllerAnimated:YES completion:nil];
}

- (void)pageAction:(UIPageControl *)page{
    self.middleImageIndex = page.currentPage;
    [self.scroll setContentOffset:CGPointMake((page.currentPage + 1) * KScreenWidth, 0) animated:YES];
}

-(void)playVedio {
    AVPlayerViewController *avPlayerVC = [[AVPlayerViewController alloc]init];
    VideoModel *model = self.modelArray[_middleImageIndex];
    avPlayerVC.url = [[NSURL alloc]initWithString:model.playUrl];
    
    //  旋转
    AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
    appDelegate.isRotation = YES;
    [self presentViewController:avPlayerVC animated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    CGFloat al = fabs((self.scroll.contentOffset.x - KScreenWidth) / KScreenWidth);
    //    NSLog(@"%f", al);
    if (self.scroll.contentOffset.x < KScreenWidth){
        self.leftView.backImage.x = self.scroll.contentOffset.x;
        self.middleView.backImage.alpha = 1 - al;
        
        self.middleView.backImage.x = -(KScreenWidth - self.scroll.contentOffset.x);
        self.leftView.backImage.alpha = al;
        
//        self.middleView.date.x = -(KScreenWidth - self.scroll.contentOffset.x);
//
//        self.leftView.date.x = self.scroll.contentOffset.x;
//        NSLog(@"%f",self.middleView.date.x);
//
//        self.middleView.changeViewButton.x = -(KScreenWidth - self.scroll.contentOffset.x) + KScreenWidth - 55;
//        self.leftView.changeViewButton.x = self.scroll.contentOffset.x + KScreenWidth - 55;
    }else {
        self.middleView.backImage.x = self.scroll.contentOffset.x - KScreenWidth;
        self.middleView.backImage.alpha = 1 - al;
        
        self.rightView.backImage.x = -(KScreenWidth * 2 - self.scroll.contentOffset.x);
        self.rightView.backImage.alpha = al;
        
//        self.middleView.date.x = self.scroll.contentOffset.x - KScreenWidth;
//        self.rightView.date.x = -(KScreenWidth * 2 - self.scroll.contentOffset.x);
//        
//        self.middleView.changeViewButton.x = self.scroll.contentOffset.x - KScreenWidth + KScreenWidth - 55;
//        self.rightView.changeViewButton.x = -(KScreenWidth * 2 - self.scroll.contentOffset.x) + KScreenWidth - 55;
    }
}


-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    NSInteger leftImageIndex, rightImageIndex;
    if (self.scroll.contentOffset.x == KScreenWidth) {
        return;
    }else if (self.scroll.contentOffset.x < KScreenWidth){
        self.middleImageIndex = (self.middleImageIndex + self.modelArray.count - 1)%self.modelArray.count;
    }else {
        self.middleImageIndex = (self.middleImageIndex + self.modelArray.count + 1)%self.modelArray.count;
    }
    
    leftImageIndex = (self.middleImageIndex + self.modelArray.count - 1)%self.modelArray.count;
    rightImageIndex = (self.middleImageIndex + 1)%self.modelArray.count;
    
    [self.middleView setValueWithVideoModel:self.modelArray[self.middleImageIndex]];
    [self.leftView setValueWithVideoModel:self.modelArray[leftImageIndex]];
    [self.rightView setValueWithVideoModel:self.modelArray[rightImageIndex]];
    
    //  重新检查是否被收藏
    [self checkCollected];
    
    
    
    //    //  根据scroll偏移量来计算出currentpage
    if (self.scroll.contentOffset.x == KScreenWidth * 2) {
        self.scroll.contentOffset = CGPointMake(KScreenWidth, 0);
    }else if (self.scroll.contentOffset.x == 0) {
        self.scroll.contentOffset = CGPointMake(KScreenWidth, 0);
    }
    self.page.currentPage = self.middleImageIndex;
}

//  判断是否已经被收藏
- (void)checkCollected{
    //    BOOL or = [[SQLiteManager shareInstance]collectedOrNotWithModel:self.modelArray[_middleImageIndex]];
    //    if (or) {
    //        self.middleView.like.selected = YES;
    ////        [self.shareButton setTitle:@""];
    //    }else {
    //        self.middleView.like.selected = NO;
    //    }
    VideoModel *model = self.modelArray[_middleImageIndex];
    if ([[CoreDataManager shareInstance]selectDataWithID:model.id]) {
        self.middleView.like.selected = YES;
    }else {
        self.middleView.like.selected = NO;
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
